import { getToken } from '@/utils/auth';
import axios, { AxiosRequestConfig, AxiosInstance, AxiosError } from 'axios';

// https://hellobike.com.cn/nhisapi/admin/p/account/loginWithPassword
// @ts-ignore
const baseUrl = import.meta.env.VITE_API_BASE_URL;
// const baseUrl = '/nhapi';

const msgMap: Record<number, string> = {
  400: '请求错误',
  401: '未授权，请重新登录',
  403: '拒绝访问',
  404: '请求出错',
  408: '请求超时',
  500: '服务器错误',
  501: '服务未实现',
  502: '网络错误',
  503: '服务不可用',
  504: '网络超时',
  505: 'HTTP版本不受支持',
};

// 根据不同的状态码，生成不同的提示信息
const showStatus = (status: number) => {
  const msg = msgMap[status] || '未知错误';
  return `${msg}(${status})，请检查网络或联系管理员！`;
};

export default function initAxios(): AxiosInstance {
  const axiosInstance = axios.create({
    baseURL: baseUrl,
    timeout: 20000,
    headers: {
      'Content-Type': 'application/json',
    },
    transformRequest: [
      function judge(data) {
        if (data instanceof FormData) {
          return data;
        }
        return JSON.stringify(data);
      },
    ],
    timeoutErrorMessage: '请求超时(20s)，请检查网络或联系管理员',
    validateStatus(status) {
      return status < 600;
    },
  });

  axiosInstance.interceptors.request.use(
    (config: AxiosRequestConfig) => {
      // let each request carry token
      // this example using the JWT token
      // Authorization is a custom headers key
      // please modify it according to the actual situation
      const token = getToken();
      if (token) {
        if (!config.headers) {
          config.headers = {};
        }
        config.headers['x-api-accesstoken'] = token;
        config.headers['x-api-clientcode'] = 'medstadmin';
        config.headers['x-api-clientid'] = '1234';
        config.headers['x-api-clientversion'] = '0.0.1';
      }
      return config;
    },
    (error) => {
      // do something
      return Promise.reject(error);
    }
  );

  // 响应拦截器
  axiosInstance.interceptors.response.use(
    (response) => {
      const { status } = response;

      if (status < 200 || status >= 300) {
        // 处理http错误，抛到业务代码
        const msg = showStatus(status);

        console.error('捕获', status, msg);

        const error = new Error(msg);
        // @ts-ignore
        error.status = status;
        return Promise.reject(error);
      }
      return Promise.resolve(response);
    },
    (error: AxiosError) => {
      console.error(error);
      if (error.message === 'Network Error') {
        error.message = '无可用网络或服务器异常，请检查网络或联系管理员！';
      }
      return Promise.reject(error);
    }
  );

  return axiosInstance;
}
